<?php 
// Start - Checker for those users who will just go to the page by typing directly in the url.
if ($_POST) { 
    include("siteTop.php"); 
    
    if(isset($_POST['documentsToReceive']))
    {
        $documentId = $_POST['documentsToReceive'];
        
    }
    else if(isset($_POST['documentsOnHand']))
    {
        $documentId = $_POST['documentsOnHand'];
    }
    else if(isset($_POST['taggedDocuments']))
    {
         $documentId = $_POST['taggedDocuments'];
    }
    else if(isset($_POST['documentId']))
    {   // Used by the search function
         $documentId = $_POST['documentId'];
    }
    else if(isset($_POST['passedDocumentId']))
    {   // Used by the view page receiving
         $documentId = $_POST['passedDocumentId'];
    }
    
    include('includes/siteConfig.php'); 

    $loggedUserId = $_SESSION['loggedUserId'];
    // CONNECT TO DATABASE
    $connect = mysql_connect($hostName,$rootName,$dBasePassword) or die ('Unable to connect!');
    mysql_select_db($dBaseName) or die ('Unable to select database!');
    
    // GET DOCUMENT ROUTE ID
    $query = 
        "
            SELECT routeId
            FROM RouteStep, MainDocument
            WHERE MainDocument.mainDocumentId = '$documentId' AND
                  MainDocument.currentStepId = RouteStep.stepId
        ";
    $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
    $row = mysql_fetch_array($result);
    $routeId = $row['routeId'];
    
    //IDENTIFY DOCUMENT DETAILS
    $query = 
        "
            SELECT *
            FROM MainDocument, DocumentSetup, DocumentRoute, RouteStep
            WHERE MainDocument.mainDocumentId = '$documentId' AND 
                  MainDocument.documentSetupId = DocumentSetup.documentSetupId AND 
                  DocumentSetup.documentSetupId = DocumentRoute.documentSetupId AND 
                  MainDocument.currentStepId = RouteStep.stepId AND DocumentRoute.routeId = '$routeId'
        ";
    $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
    $row = mysql_fetch_array($result);
    
    $routeName = $row['routeName'];
    $documentName = $row['documentName'];
    $subRouteId = $row['subRouteId'];
    $stepNumber = $row['stepNumber'];
    $stepId = $row['stepId'];
    $documentAction = $row['action'];
    $userActivity = $row['userActivity'];
    $docStatus = $row['status'];
    
    if (is_null($subRouteId)) {
        $subRouteIsNull = 1;
        $subRouteString = "tempval";
    }
    
    else {
        $subRouteIsNull = 0;
        $subRouteString = $subRouteId;
    }    
    
    // IDENTIFY IF THE LOGGED USER HAS THE DOCUMENT, IF YES > GET ROLE, ELSE > NO BUTTON
    $query = 
        "
            SELECT *
            FROM Log, MainDocument
            WHERE Log.documentId = '$documentId' AND
                  Log.userId = '$loggedUserId' AND
                  Log.stepId = MainDocument.currentStepId
            ORDER BY logDateTime DESC
        ";
    $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
    $row = mysql_fetch_array($result);
    
    // THE LOGGED USER HAS THE DOCUMENTS
    if ($row['activity'] == "Received") {        
        //IDENTIFY ROLE OF THE USER
        $query = 
            "
                SELECT role
                FROM MainDocument, RouteStep
                WHERE MainDocument.mainDocumentId = '$documentId' AND 
                      MainDocument.currentStepId = RouteStep.stepId
            ";
        $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
        $row = mysql_fetch_array($result);
        
        //SAVE THE ROLE OF THE USER TO $activityFlag
        $activityFlag = $row['role'];
        
        $docCancelled = "";
        // IDENTIFY IF THE DOCUMENT HAS BEEN CANCELLED.
        if ($documentAction == 'Cancelled') {
            $activityFlag = 4;
            $docCancelled = "1";
        }
    }
    
    // THE LOGGED USER DOESN'T HAVE THE DOCUMENTS
    else {
        error_log("WALA SAKIN YUNG DOCUMETS!!");
        $activityFlag='0';
    }
    
    
    // GET THE USERID OF THE ORIGIN
    $query = 
        "
            SELECT *
            FROM MainDocument, RouteStep
            WHERE mainDocumentId = '$documentId' AND 
                  status = 'Active' AND
                  action = 'Received' AND
                  originId = '$loggedUserId' AND
                  MainDocument.currentStepId = RouteStep.stepId AND
                  RouteStep.canBeCancelled = '1';
        ";
    $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
    
    // ORIGIN CAN CANCEL THE DOCUMENT.
    if (mysql_num_rows($result) > 0) {
        $loggedUserIsOrigin = 1;
    }
    
    // ORIGIN CANNOT CANCEL THE DOCUMENT.
    else {
        $loggedUserIsOrigin = 0;
    }
    
    error_log("~~~~~~~~~~~~~~ACTIVITY FLAG === $activityFlag");
?>
<!--    
    Created By : Julian Ponce
    B.S. Computer Science - De La Salle Canlubang
    September 15, 2011
    Description :
    
    This page allows the user to send the documents (Main Document and Attachments). 
    This page is used in normal sending, approving / disapproving, canceling, rejecting
    and archiving.

    FLAGS USED :
        activityFlag = 0 (View page for everyone. No buttons. T)
        activityFlag = 1 (normal sending)
        activityFlag = 2 (approve/return for revisions/disapprove)
        activityFlag = 3 (archiving)
        activityFlag = 4 (Send for Archiving), this means that the origin cancelled the document.
        
        loggedUserIsOrigin = (cancel if loggedUser == ORIGIN)
        
-->
    
<!-- HEADER START -->
    <!--JAVASCRIPT SOURCES-->
    <script src="js/jquery-1.6.2.min.js"></script>

    <!--ACTUAL JS SCRIPTS AND JQUERIES-->
    <script type="text/javascript">
    var missingAttachments = new String();
    var checkMergedAdded = new String();
    
        // [START] DOCUMENT READY FUNCTION
        jQuery(document).ready(function(){
            
            /*******************************************************************/
            /************** [START] INITIALIZATION JQUERIES ********************/
            /*******************************************************************/
            activityFlagJS = <?php echo $activityFlag; ?>;
            subRouteIsNull = <?php echo $subRouteIsNull; ?>; 
            loggedUserIsOrigin = <?php echo $loggedUserIsOrigin; ?>;            
            
            if (subRouteIsNull) {
                subRouteStringJS = "NULL";
            }
            
            else {
                subRouteStringJS = "<?php echo $subRouteString; ?>";
            }
           
            //CHANGE THE DEFAULT SUB ROUTE
            jQuery("#defaultSubRoute").val(subRouteStringJS);
            jQuery("#defaultSubRoute").text(subRouteStringJS);
            
            addLogInfo(".logInfoDiv", "<?php echo $documentId; ?>", "fromBase");    // Add Logs        
            addTrackDoc("#logMainDocTrackRow", "<?php echo $documentId; ?>"); // Add Track document

            //IDENTIFY WHICH BUTTON/SCREENLETS TO SHOW
            switch (activityFlagJS) {
                // JUST VIEWING
                case 0 :
                    jQuery("#attachmentsScreenlet").hide();
                    jQuery("#attachmentsTD").hide();
                    break;
                
                // NORMAL SENDING
                case 1 : 
                    jQuery("#sendButton").show();
                    jQuery("#keepButton").show();
                    break;
                    
                // EVALUATE (APPROVE, RETURN FOR REVISIONS, DISAPPROVE)    
                case 2 :
                    jQuery(".evaluateButtons").show();
                    jQuery("#keepButton").show();
                    break;
                    
                // ARCHIVE    
                case 3 : 
                    jQuery("#archiveButton").show();
                    jQuery("#keepButton").show();
                    break;
                    
                // IF DOC WAS CANCELLED
                case 4 : 

                    // AJAX IN IDENTIFYING IF THE HOLDER OF THE CANCELLED DOCUMENTS IS THE ARCHIVER
                    jQuery.ajax({
                        type : 'POST',
                        url : 'ajaxRequests/checkUserForCancelled.php',
                        dataType : 'json',
                        async : false,
                        data: {
                            holderUserId : "<?php echo $loggedUserId; ?>",
                            routeId : "<?php echo $routeId; ?>"
                        },
                        success : function(data){
                            
                            // IF HOLDER = ARCHIVER, show ARCHIVE BUTTON
                            if (data) {
                                jQuery("#archiveButton").show();
                                jQuery("#sendForArchivingButton").hide();
                            }
                            
                            // IF HOLDER IS NOT ARCHIVER, SHOW SEND FOR ARCHIVING BUTTON (Send)
                            else {
                                jQuery("#sendForArchivingButton").show();
                                jQuery("#archiveButton").hide();
                            }
                        },
                        error : function() {

                        }
                    });
                    jQuery("#subRouteScreenlet").hide();
                    jQuery("#docAction").addClass("errorMessage");
                    break;
                    
            }
            
            //IF LOGGED USER = ORIGIN, HE/SHE CAN CANCEL THE DOCUMENT.
            if (loggedUserIsOrigin) {
                jQuery("#cancelButton").show();
            }
       
            
            // AJAX IN GETTING EXISTING ATTACHMENTS
            jQuery.ajax({
                type : 'POST',
                url : 'ajaxRequests/getMainDocAttachments.php',
                dataType : 'json',
                async : false,
                data: {
                    documentId : "<?php echo $documentId; ?>"
                },
                success : function(data){
                    if (data) {
                        jQuery.each(data, function(index, data) {
                            jQuery("#lastRowAttachment").before("<tr><td><input type='hidden' class='existingAttachmentsName' value='"+data.documentSetupId+"'/><input type='text' name='attachmentStatus' id='attachmentStatus_" + data.attachmentId + "' value='Attached_" + data.attachmentId + "' style='display:none;' class='attachmentStatus' /> <a href='javascript:void(0)' class='shwAttchInfo' id='theatre__" + data.attachmentId + "'>" + data.attachmentId + "</a></td><td><span>" + data.documentName + "</span></td><td align='center'><input type='Button' name='attchTransacBtn_" + data.attachmentId + "' id='attchTransacBtn_" + data.attachmentId + "' class='siteRedButton attchTransacBtn' value='Detach'/></td></tr>");
                        });
                        checkAttachments();
                    }
                },
                error : function() {

                }
            });
            
            // AJAX IN GETTING REQUIRED ATTACHMENTS
            jQuery.ajax({
                type : 'POST',
                url : 'ajaxRequests/getRequiredAttachments.php',
                dataType : 'json',
                async : false,
                data: {
                    routeId : <?php echo $routeId; ?>,
                    stepNumber : <?php echo $stepNumber; ?>,
                    subRouteId : subRouteStringJS
                },
                success : function(data){
                    if (data.documentName != "none") {
                        currentDiv = "";

                        jQuery.each(data, function(index, data) {
                          jQuery("#reqdAttachments").append("<div style='margin-bottom:2%;'><input type='hidden' value='"+data.documentSetupId+"' class='requiredAttachmentsName'/><span>" + data.documentName +"</span><input style='margin-right:40%;float:right;font-size:10px; padding-right: 1px;padding-left: 1px;padding-top: 1px;padding-bottom: 1px;' type='button' class='siteGreenButton addAttachmentButton' title='"+data.documentName+"' value='Add' id='requiredButton_"+data.documentSetupId+"'/><img id='requiredCheck_" + data.documentSetupId + "' style='float:right; display:none; margin-right:40%;' src='images/checkmark.png' height='20px' width='20px'/></div>");

                        });
                        //jQuery("#reqdAttachments").html(currentDiv);
                        
                        checkAttachments();
                    }
                        
                    else {
                        jQuery("#reqdAttachments").html("None.");
                    }

                },
                error : function() {
                    alert("Error in getting the available document routes.");
                }
            });
            
            // [START] IF SUB ROUTE IS NULL, IDENTIFY IF THERE ARE SUB ROUTES FOR NEXT STEP NUMBER
            if (subRouteIsNull) {
                jQuery("#subRouteId").val("NULL");
                // AJAX IN IDENTIFYING IF THE USER WILL CHOOSE A SUBROUTE.
                jQuery.ajax({
                    type : 'POST',
                    url : 'ajaxRequests/checkSubRoute.php',
                    dataType : 'json',
                    async : false,
                    data: {
                        stepId : "<?php echo $stepId; ?>"
                    },
                    success : function(data){
                        if (data && (activityFlagJS != 0) ) {
                            jQuery.each(data, function(index, data) {
                                jQuery("#defaultSubRoute").before("<option value='"+data.subRouteId+"'>"+data.subRouteName+"</option>");
                            });
                            
                            //DELETE DEFAULT SUB ROUTE (NULL)
                            $("#defaultSubRoute").remove();
                        }     
                        
                        else {
                            jQuery("#subRouteScreenlet").hide();
                            
                        }
                    },
                    error : function() {
                        alert("fail [checkSubRoute.php AJAX]");
                    }
                });
            } // [END] IF SUB ROUTE IS NULL, IDENTIFY IF THERE ARE SUB ROUTES FOR NEXT STEP NUMBER
            
            // IF SUB ROUTE IS NOT NULL. DO THIS.
            else {
                jQuery("#subRouteId").val("<?php echo $subRouteId; ?>");
                jQuery("#subRouteScreenlet").hide();
            } 
            
            // GET EXISTING REMARKS
            getExistingRemarks();
            
            jQuery("#remarkScreenlet").animate({ scrollTop: 60000 }, 'slow'); 
            /*******************************************************************/
            /************** [END] INITIALIZATION JQUERIES **********************/
            /*******************************************************************/
            
            /************** [START] PETER AGNO CODES ***************************/
            
            // Start - Do the following when the ok button is performed
            jQuery('.okTheatreBtn').live("click",function() {
                theButtonValue = jQuery("#prevBtn").val();
                buttonId = this.id;
                tempSubstr = buttonId.split('_');
                
                // Do not proceed if input is empty
                if ( jQuery("#theatreRemarks").val() != '' && jQuery("#theatreRemarks").val() != ' ' ) {
                    // Set the confirmation message
                    if ( tempSubstr[1] == "returning" ) {
                        theMessage = "Are you sure that the documents will be returned for revisions?";
                    }
                    else {
                        if ( tempSubstr[1] == "disapproving" ) {
                            theMessage = "Are you sure that the documents will be disapproved?";
                        }
                        else {
                            theMessage = "Are you sure that the documents will be cancelled?";
                        }
                    }
                    
                    // Ask the user for confirmation
                    chosenCnfrm = confirm(theMessage);
                    if ( chosenCnfrm == true ) {
                        jQuery("#textAreaRemarks").val( jQuery("#theatreRemarks").val() );
                        jQuery(".theatreTransparent").click();
                        
                        recordViewPageActions(theButtonValue);
                    }
                }
                else {
                    alert("Input the remarks for " + tempSubstr[1] + " the documents.");
                }
            }); // End - Do the following when the ok button is performed
            
            // Start - cancel button
            jQuery("#cancelTheatreBtn").live("click",function() {
                jQuery(".theatreTransparent").click();
            }); // End - Close button
            
            // Start - remove theatreTransparent and theatreContentBox
            jQuery(".theatreTransparent").live("click",function() {
                jQuery(".theatreTransparent").remove();
                jQuery(".theatreContentBox").remove();
            }); // End - remove theatreTransparent and theatreContentBox
            
            
            // START - JQUERIES FOR LOGS
            jQuery('.extendButton').live("click",function() {

               buttonId = this.id;
               buttonValue = jQuery("#"+buttonId).val();
               
               if (buttonValue == "View") {
                   jQuery("."+buttonId).show();
                   jQuery("#"+buttonId).val("Hide");
               }
               else {
                     jQuery("."+buttonId).hide();
                    jQuery("#"+buttonId).val("View");
               }
            }); // END - JQUERIES FOR LOGS
            
            // INCLUDE JQUERUES FOR SHOWING DOCUMENT LOG
            <?php include('includes/jqueries/jQShowDocLog.php'); ?>
                
            // INCLUDE JQUERUES FOR SHOWING TRACK DOCUMENT
            <?php include('includes/jqueries/jQAddTrackDoc.php'); ?>

            // INCLUDE JQUERIES FOR INFORMATION BUTTON
            <?php include('includes/jqueries/jQLogInfoIcn.php'); ?>
                
            // INCLUDE JQUERUES FOR TRACKING
            <?php 
//                include('includes/jqueries/jQTrackDoc.php'); 
            ?>

            // Start - Change the color of the track circles if it was hovered and unhovered
            function changeCircle(buttonId, theStepNum, theTotalStepNum, theColor, isHover) {
                var circleVersion = "5", fileFormat = "png";

                // Prepare the hover
                if ( isHover == true ) {
                    varHov = "hov";
                }
                else {
                    varHov = "nothov";
                    
                    // Prepare the file format and varHov for blinking of current track point
                    if ( theColor == "ylw" ) {
                        varHov = "blink";
                        fileFormat = "gif";
                    }
                }

                // Prepare the variables
                if ( theStepNum  == 1 ) {
                    // Prepare the position
                    varPosition = "frst";
                    varFolder = "first";
                }
                else if ( theStepNum == theTotalStepNum ) {
                    // Prepare the position
                    varPosition = "last";
                    varFolder = "last";
                }
                else {
                    // Prepare the position
                    varPosition = "cntr";
                    varFolder = "center";
                }

                jQuery("#"+buttonId).attr("src", "images/trackDoc/version"+circleVersion+"/"+varFolder+"/"+theColor+"_"+varHov+"_"+varPosition+"."+fileFormat);
            } // End - Change the color of the track circles if it was hovered and unhovered

            // START - JQUERUES FOR TRACKING
            jQuery(".trackCircles").hover(
                function (mousePtr) {
                    // START - DO THE FOLLOWING DURING HOVER
                    buttonId = this.id;

                    // MODIFY THE POSITION SO THAT IT IS NOT THAT FAR FROM THE CIRCLE
                    topValue = mousePtr.pageY - 10;
                    leftValue = mousePtr.pageX - 130;

                    // MODIFY THE CSS POSITION BEFORE SHOWING
                    jQuery(".trackInvisibleInfo").css({ 'display': 'none', 'top': topValue, 'left': leftValue });

                    // CHECK FOR THE APPROPRIATE IMAGE
                    tempSubstr = buttonId.split('__');
                    theStepNum = tempSubstr[3];
                    theTotalStepNum = tempSubstr[4];

                    if ( tempSubstr[1] == "ylw" )
                        changeCircle(buttonId, theStepNum, theTotalStepNum, "ylw", true);
                    else {
                        if ( tempSubstr[1] == "grn" ) 
                            changeCircle(buttonId, theStepNum, theTotalStepNum, "grn", true);
                        else
                            changeCircle(buttonId, theStepNum, theTotalStepNum, "gry", true);
                    }


                    // START - AJAX THE NEEDED INFORMATIONS
                    jQuery.ajax({
                        type : 'POST',
                        url : 'ajaxRequests/trackDocInfo.php',
                        dataType : 'json',
                        async : false,
                        data: {
                            documentId : tempSubstr[0],
                            stepId : tempSubstr[2]
                        },
                        success : function(data){
                            // SET THE INFORMATION IN THE DIV
                            setInfo = "<table style='border:0; margin-bottom:0px;'>";
                            setInfo += "<tr><td style='padding-left:0px; border:0;' class='trackTableTd'>Step Number : </td><td style='border:0;'>"+ tempSubstr[5]+"</td></tr>";

                            if ( data.firstName != 'None' )
                                setInfo += "<tr><td style='padding-left:0px; border:0;' class='trackTableTd'>User : </td><td style='border:0;'>"+ data.firstName + data.middleName + data.lastName+"</td></tr>";

                            setInfo += data.deptPos;

                            // DISPLAY ROLE
            //                            if ( data.firstName != 'None' )
            //                                setInfo += "<tr><td style='padding-left:0px; border:0;' class='trackTableTd'>Role : </td><td style='border:0;'>"+ data.activity+"</td></tr>";

                            setInfo += "</table>";
                            // PUT THE INFORMATION IN THE DIV
                            jQuery(".trackInvisibleInfo").html(setInfo);
                            jQuery(".trackInvisibleInfo").show();
                        },
                        error : function() {
                            alert("Error in getting the document information.");
                        }
                    }); // END - AJAX THE NEEDED INFORMATIONS
                    // END - DO THE FOLLOWING DURING HOVER
                }, 
                function () {
                    // START - DO THE FOLLOWING DURING NOT HOVER
                    buttonId = this.id;

                    // CHECK FOR THE APPROPRIATE IMAGE
                    tempSubstr = buttonId.split('__');
                    theStepNum = tempSubstr[3];
                    theTotalStepNum = tempSubstr[4];

                    if ( tempSubstr[1] == "ylw" )
                       changeCircle(buttonId, theStepNum, theTotalStepNum, "ylw", false);
                    else {
                        if ( tempSubstr[1] == "grn" )
                            changeCircle(buttonId, theStepNum, theTotalStepNum, "grn", false);
                        else
                            changeCircle(buttonId, theStepNum, theTotalStepNum, "gry", false);
                    }


                    jQuery(".trackInvisibleInfo").hide();
                    // END - DO THE FOLLOWING DURING NOT HOVER
                }); // END - JQUERUES FOR TRACKING 
            // End - Include jquery for tracking
                
            <?php
                // INCLUDE JQUERUES FOR THEATRE BOX IN SHOWING AN ATTACHMENT
                include('includes/jqueries/jQShwAttchInfo.php'); 
            ?>
                                                                    
            // Include document on ready jQuery for hiding scroll bars of track document if necessary
            <?php include('includes/jqueries/jQHideDivTrckScroll.php'); ?>
            
            // *** Start - The following are the includes for viewing page of attachment. ***
            <?php 
                // INCLUDE JQUERUES FOR SHOWING DOCUMENT INFORMATION
                include('includes/jqueries/jQShowDocInfo.php'); 
                
                // INCLUDE JQUERUES FOR SHOWING DOCUMENT LOG
                include('includes/jqueries/jQShowDocLog.php');
                
                // INCLUDE JQUERIES FOR INFORMATION BUTTON
                include('includes/jqueries/jQLogInfoIcn.php');
                
                // INCLUDE JQUERIES FOR ADDING THE ATTACHMENT TRANSACTION SCREENLETS
                include('includes/jqueries/jQAttchTransac.php');
                
                // INCLUDE JQUERUES FOR SEND ATTACHMENT SCREENLET
                // Flag for showing the send attachment screenlet when onloading
                ?>
                var changePos = false;
                <?php
                include('includes/jqueries/jQSendAttach.php');
                
                // INCLUDE JQUERUES FOR ACKNOWLEDGE SENT ATTACHMENT SCREENLET
                include('includes/jqueries/jQAckSentAttach.php');
                
                // INCLUDE JQUERUES FOR ARCHIVE ATTACHMENT
                include('includes/jqueries/jQArchiveAttach.php');
            ?>
            
            /************** [END] PETER AGNO CODES ***************************/
            
            
            /*******************************************************************/
            /******************* [START] JQUERY CLICKS**************************/
            /*******************************************************************/
            
            // [START] JQUERY FOR CONSILIDATED VIEW PAGE TRANSACTION BUTTONS 
            // (Send, Approve, Return for Revisions, Rejct, Cancel Transaction, 
            //  Send For Archiving, Archive)
            jQuery('.viewPageButtons').live("click",function() {
                theButton = this;
                
                //CHECK ALL REQUIRED ATTACHMENTS IF COMPLETE.
                attachmentsComplete = checkAttachments();

                //IF ALL ATTACHMENTS ARE COMPLETE, PROCEED TO AJAX.
                if ((attachmentsComplete) || theButton.id == "disapproveButton" || theButton.id == "returnForRevisionsButton" || theButton.id == "cancelButton" || theButton.id == "keepButton" || (activityFlagJS == 4)) {
                    if ( theButton.id == "disapproveButton" || theButton.id == "returnForRevisionsButton" || theButton.id == "cancelButton" ) {
                        // Create the theatre for remarks for returning or disapproving
                        // Add transparent box and content box
                        jQuery(".body").prepend("<div class='theatreTransparent'> </div>");
                        jQuery(".body").prepend("<div class='theatreContentBox'></div>"); 

                        // Add theatreContent
                        jQuery(".theatreContentBox").append("<div class='theatreContent'></div>");

                        // Add headers
                        if ( theButton.id == "returnForRevisionsButton" ) {
                            actionDoing = "returning";
                            jQuery(".theatreContent").append("<h1>Return For Revisions</h1>");
                        }
                        else {
                            if ( theButton.id == "disapproveButton" ) {
                                actionDoing = "disapproving";
                                jQuery(".theatreContent").append("<h1>Disapprove</h1>");
                            }
                            else {
                                actionDoing = "cancelling";
                                jQuery(".theatreContent").append("<h1>Cancel</h1>");
                            }
                        }

                        // Add messageBox
                        jQuery(".theatreContent").append("<br/><div class='messageBox successMessage successMessage_fromTheatre' style='display:none;'><div id='successMessages' class='successMessages_fromTheatre'></div></div>");

                        // Add message about the remarks
                        jQuery(".theatreContent").append("<br/><div class='remarksDiv'>Please input the remarks for " + actionDoing + " the document:</div>");

                        // Add the text area for remarks
                        jQuery(".theatreContent").append("<br/><textarea rows='4' cols='69' style='background-color: khaki' id='theatreRemarks'></textarea>");

                        // Add ok, cancel button, and the previous button clicked
                        jQuery(".theatreContent").append("<br><br><input type='button' id='okTheatreBtn_"+actionDoing+"' name='okTheatreBtn' value='Ok' class='siteGreenButton okTheatreBtn'>");
                        jQuery(".theatreContent").append("&nbsp <input type='button' id='cancelTheatreBtn' name='cancelTheatreBtn' value='Cancel' class='siteGreenButton'><input type='text' style='display:none;' id='prevBtn' value='" + theButton.value + "' />");

                        jQuery("#theatreRemarks").focus();
                    }

                    else {
                            recordViewPageActions(theButton.value);                 
                    }
                } // END OF COMPLETE ATTACHMENTS
                
                //IF REQUIRED ATTACHMENTS IS NOT COMPLETE, DISPLAY ERROR MESSAGE.
                else {
                        alert("Please check again the required attachments.");
                }
                
            }); // [END] JQUERY FOR CONSILIDATED VIEW PAGE TRANSACTION BUTTONS 
            

            // [START] ADD BUTTON CLICK
            jQuery(".addAttachmentButton").live("click",function() {
                // Add transparent box and content box
                jQuery(".body").prepend("<div class='theatreTransparent'> </div>");
                jQuery(".body").prepend("<div class='theatreContentBox'> </div>");               
               
                // Add contents of the popup
                documentNameId= jQuery(this).attr('id');
                documentNameTitle= jQuery(this).attr('title');
               
                // Split documentNameId in order to get documentSetupId (tempSubstr[1])
                tempSubstr = documentNameId.split('_');
                
                jQuery(".theatreContentBox").append("<div class='theatreContent'><h1>Add Attachment </h1> <br> <span class='screenlet'>Attachment Information</span> </div>");
                jQuery(".theatreContent").append("<table><tr><td>Document Name</td><td id='documentName'> " +                            
                    "</td></tr> <tr><td>Document ID</td><td> <input type='text' id='theatreId'> </td></tr><tr><td></td><td><span id='successMessage' class='successMessage'></span><span id='errorMessage' class='errorMessage'></span></td></tr>  </table>");
                jQuery(".theatreContent").append("<input type='button' id='theatreButton' value='Add' class='siteGreenButton'> <input type='button' id='cancelTheatreButton' value='Cancel' class='siteGreenButton'>  ");
                
                jQuery("#theatreId").focus();
                
                // [START] IF ADD = "OTHERS"
                if(documentNameId=="addAttachmentButton") {
                    jQuery("#documentName").append("<select value='namedropdown' id='theatreName' class='documentList'> </select>");
                  
                    // Get all documents in DocumentSetup
                    jQuery.ajax({
                        type : 'POST',
                        url : 'ajaxRequests/getDocumentList.php',
                        dataType : 'json',
                        data: {
                            docType : "Attachment"
                        },
                        success : function(data){
                            
                            // List all documents in a drop-down
                            jQuery.each(data, function(index, data) {
                                jQuery("#theatreName").append("<option value='"+data.documentSetupId+"'>"+data.documentName+"</option>");
                            });                        
                        },
                        error : function() {
                            alert("fail ajax get document name in theatre");
                        }
                    }); // END - Get all documents in Document Setup
                } // [END] IF ADD = "OTHERS"
                
                
                // [START] IF ADD = "EXIST IN REQUIRED"
                else {
                 jQuery("#documentName").append("<input type='hidden' id='theatreDocSetupId' value='"+tempSubstr[1]+"'><input type='hidden' id='theatreName' value='"+documentNameId+"'><div>"+documentNameTitle+" </div>");
                } // [END] IF ADD = "EXIST IN REQUIRED"
              
                
                // THEATREID ON BLUR, VALIDATE DOCUMENT ID IF IT ALREADY EXIST, IF YES, IF IT CAN BE MERGED.
                jQuery("#theatreId").live("blur",function() {
                if (this.value != "") {  
                    jQuery.ajax({
                        type : 'POST',
                        url : 'ajaxRequests/checkDocumentId.php',
                        dataType : 'json',
                        data: {
                            docId : jQuery("#theatreId").val(),
                            docType : "Attachment"
                            },
                            success : function(data){
                                jQuery("#errorMessage").html("");
                                jQuery("#successMessage").html("");

                                // ATTACHMENT ID ALREADY EXIST, CHECK IF THE USER WANTS TO MERGE AN ATTACHMENT.
                                if (data.idExist == "1") {
                                     
                                   // CHECK IF ATTACHMENT IS ON HAND AND HAS NO MAIN DOCUMENT.
                                   // THIS CAN BE SUBJECTED FOR MERGING.
                                    jQuery.ajax({
                                        type : 'POST',
                                        url : 'ajaxRequests/checkAttachmentForMerge.php',
                                        dataType : 'json',
                                        data: {
                                            attachmentId : jQuery("#theatreId").val()
                                        },
                                        success : function(data){
                                           if (data) {
                                              jQuery("#successMessage").html("Attachment will be merged to <?php echo $documentId; ?>");
                                              checkMergedAdded = "Merged";
                                           }
                                           
                                           else {
                                               jQuery("#errorMessage").html("Document ID already exist.");
                                               jQuery("#theatreId").val("");
                                               jQuery("#theatreId").focus();
                                           }
                                           
                                        },
                                        error : function() {
                                            alert("fail ajax on getting document step Id");
                                        }
                                    }); 
                                } // [END] IF DOCUMENT ID ALREADY EXIST
                                
                                // [START] IF DOCUMENT ID DOESN'T EXIST
                                else if (data.idExist == "0"){
                                    checkMergedAdded = "Added";
                                    idAlreadyExist = 0;
                                    currentValTheatreId = jQuery("#theatreId").val();
                                    
                                    //ITERATE ALL ATTACHMENT ID's' TO VERIFY THAT THEATRE ID IS UNIQUE
                                    jQuery(".attachmentStatus").each(function(index) {
                                        tempDocId = "";
                                        tempDocString = this.value;
                                        tempSubstr = tempDocString.split('_');

                                        // GET DOCUMENT ID's
                                        tempDocId = tempSubstr[1];
                                        
                                        
                                        if (tempDocId == currentValTheatreId) {
                                            jQuery("#errorMessage").html("Document ID already exist.");
                                            jQuery("#theatreId").val("");
                                            jQuery("#theatreId").focus();
                                            alert("Document ID already exist.");
                                        }

                                    });
                                    
                                    
                                } // [END] IF DOCUMENT ID DOESN'T EXIST
                            },
                            error : function() {
                                alert("fail ajax on blur theatreID");
                            }
                        }); 
                    } // [END] ON THEATREID BLUR, IF TEXTBOX HAS VALUE

                    // [START] ON THEATREID BLUR, IF TEXTBOX DOESN'T HAVE VALUE
                    else {
                        jQuery("#successMessage").html("");
                        jQuery("#errorMessage").html("");
                    } // [END] ON THEATREID BLUR, IF TEXTBOX DOESN'T HAVE VALUE

                }); // [END] - THEATREID ON BLUR
                
                // IF THEATRE BUTTON WAS CLICKED
                jQuery("#theatreButton").click(function(){
                    theatreId = jQuery("#theatreId").val();
                    theatreName = jQuery("#theatreName").val();
                    theatreLabel = jQuery("#theatreLabels").val();
                   
                   
                    // [START] IF ADDATTACHMENTBUTTON (OTHERS), GET SELECTED ATTACHMENT FROM DROP-DOWN   
                    if(documentNameId=="addAttachmentButton"){
                        theatreActualName = jQuery("#theatreName option:selected").text();
                        documentNameId = jQuery("#theatreName option:selected").val();
                        theatreActualDocSetupId = jQuery("#theatreName option:selected").val();
                    }
                   
                    else {
                        theatreActualName = documentNameTitle;
                        theatreActualDocSetupId = jQuery("#theatreDocSetupId").val();    
                    }
                   
                   // GETS THE DOCUMENT SETUP ID FROM THE SELECTED ATTACHMENT
                   if( theatreId == ""){
                       alert("Please input the Attachment ID.");
                   }
                   
                   else{  
                       if (checkMergedAdded == "Merged" || checkMergedAdded == "Added") {
                            jQuery("#lastRowAttachment").before("<tr id ='attachTr_"+theatreId+"'>"+
                                "<td><input type='hidden' class='existingAttachmentsName' id='docSetupId_"+theatreId+"' value='"+theatreActualDocSetupId+"'/><input type='hidden' name='attachmentStatus' id='attachmentStatus_"+theatreId+"' value ='"+checkMergedAdded+"_"+theatreId+"' class='attachmentStatus'/>"+ theatreId +"</td>"+
                                "<td>"+ theatreActualName +"</td>"+
                                "<td align='center'><img id='delImg_" + theatreId + "' class='removeAttachment' src='images/ximage.png' height='20px' width='20px' style='cursor: pointer;'/></td> "+
                                "</tr>"
                            );
                       }
                       
                       jQuery(".theatreTransparent").click();
                       checkAttachments();
                   }
                }); // RETURN VALUES
            checkAttachments();
            }); //END  - ADD ATTACHEMENT JQUERY
            
            // [START] IF CANCEL BUTTON WAS CLICKED
            jQuery("#cancelTheatreButton").live("click", function(){
                jQuery(".theatreTransparent").click();
            }); // [END] IF CANCEL BUTTON WAS CLICKED
             
            
            // [START] CLICK TRANSPARENT, DESTROY POP-UP
            jQuery(".theatreTransparent").live("click",function() {
                jQuery(".theatreContent").remove();
                jQuery(".theatreTransparent").remove();
                jQuery(".theatreContentBox").remove();
            }); // [END] CLICK TRANSPARENT, DESTROY POP-UP
            
            // [START] - DETACH and RE-ATTACH BUTTON WHEN CLICKED
            jQuery('.attchTransacBtn').live("click",function() {
                buttonId = this.id;
                tempSubstr = buttonId.split('_');
                
                if ( jQuery("#"+buttonId).val() == "Detach" ) {
                    jQuery("#"+buttonId).val("Reattach");   // Change the button name
                    jQuery("#"+buttonId).attr('class', 'siteGreenButton attchTransacBtn');  // Change color
                    jQuery("#attachmentStatus_"+tempSubstr[1]).val("Detached_"+tempSubstr[1]);    // update attachmentStatus of that attachment
                }
                else {
                    jQuery("#"+buttonId).val("Detach");     // Change the button name
                    jQuery("#"+buttonId).attr('class', 'siteRedButton attchTransacBtn');    // Change color
                    jQuery("#attachmentStatus_"+tempSubstr[1]).val("Attached_"+tempSubstr[1]);    // update attachmentStatus of that attachment
                }
            }); // [END] - DETACH and RE-ATTACH BUTTON WHEN CLICKED
            
                        
            // [START] WHEN CLICKED DASHBOARD BUTTON. REDIRECT TO DASHBOARD.PHP
            jQuery("#dashboardButton").live("click", function() {
                window.location = "dashboard.php";
            }); // [END] WHEN CLICKED DASHBOARD BUTTON. REDIRECT TO DASHBOARD.PHP
            
            // [START] WHEN CLICKED REMOVE / "X", IN ORDER TO REMOVE NEWLY ADDED/MERGED ATTACHMENT
            jQuery(".removeAttachment").live("click", function() {
                tempDocString = this.id;
                tempSubstr = tempDocString.split('_');

                // GET DOCUMENT ID's
                tempDocId = tempSubstr[1];
                
                chosenCnfrm = confirm("Are you sure you want to remove attachment "+tempDocId+"?");
                
                // IF CONFIRM, REMOVE ATTACHMENT ID IN CORRESPONDING TR.
                if (chosenCnfrm) {
                    jQuery("#attachTr_" + tempDocId).remove();
                    checkAttachments();
                }
            }); // [END] WHEN CLICKED REMOVE / "X", IN ORDER TO REMOVE NEWLY ADDED/MERGED ATTACHMENT
            
            //START - remark, click on text area
            jQuery("#remarkInput").live("click",function() {
                jQuery(this).val("");
            });
            
            //START - SAVE REMARK
            jQuery("#remarkInput").keypress(function(e){

               // IF ENTER.
                if((e.keyCode == 13) && this.value != "" ) {
                    tempUserFullName = "<?php echo $_SESSION['firstName'] . ' ' . $_SESSION['lastName']; ?>";
                    tempRemark = jQuery("#remarkInput").val();
                    jQuery.ajax({
                        type : 'POST',
                        url : 'ajaxRequests/saveRemark.php',
                        dataType : 'json',
                        async : false,
                        data: {
                            documentId : "<?php echo $documentId; ?>",
                            userId : "<?php echo $loggedUserId ?>",
                            remark : tempRemark
                        },
                        success : function(data){
                          
                            jQuery("#noRemarkDefault").hide();
                            jQuery("#remarkHeader").show();
                            tempDateTime = JS_DateTime();
                            jQuery("#lastRemark").before("<tr><td><span style='font-weight:bold;'>"+tempUserFullName+" : </span><br><span>"+tempRemark+"</span></td><td>"+tempDateTime+"</td></tr>");
                        },
                        error : function() {
                            alert("fail saveRemark.php");
                        }
                    });
                    jQuery("#remarkInput").blur();
                    jQuery("#remarkScreenlet").animate({ scrollTop: 60000 }, 'slow');
                    jQuery("#remarkInput").val("Write a remark.");

                }
            });
            
            /*******************************************************************/
            /********************* [END] JQUERY CLICKS**************************/
            /*******************************************************************/
            
            
            
            /*******************************************************************/
            /******************* [START] FUNCTIONS LIST ************************/
            /*******************************************************************/
            
            // [START] checkAttachments FUNCTION
            // Desc : This function checks if all required attachments are complete.
            function checkAttachments() {
                missingAttachments = "";
                completeFlag = 1;
                
                jQuery(".requiredAttachmentsName").each( function (index) {
                    requiredAttachment = this.value;
                    found = 0;
                    
                    jQuery(".existingAttachmentsName").each(function(index) {
                        existingAttachment = this.value;
                        if (requiredAttachment == existingAttachment) {
                            found = 1;
                            
                        }
                    });
                    
                    if (found) {
                        jQuery("#requiredButton_"+requiredAttachment).hide();
                        jQuery("#requiredCheck_"+requiredAttachment).show();
                    }
                    
                    else if (!found) {
                        completeFlag = 0;
                        jQuery("#requiredButton_"+requiredAttachment).show();
                        jQuery("#requiredCheck_"+requiredAttachment).hide();
                    }
                    
                });
                
                return completeFlag;
            } 
            // [END] checkAttachments FUNCTION
            
            
            // [START] recordViewPageActions FUNCTION
            // Desc : This recordViewPageActions function will be activated when the view page sending
            // transaction buttons was clicked. (Send, Approve, Return for Revisions, Disapprove, 
            // Cancel Transaction, Archive, and Send for Archiving)
            function recordViewPageActions(theButtonValue) { 
            jQuery("#plsWaitDiv").show();
            jQuery(".viewPageButtons").hide();
            jQuery("#dashboardButton").hide();
            
                buttonValue = theButtonValue;
                attachedCount = 0;
                detachedCount = 0;
                addedCount = 0;
                mergedCount = 0;
              
                attachedString = "";
                detachedString = "";
                addedString = "";
                addedDocSetupIdString = "";
                mergedString = "";
                
                // ITERATE ALL ATTACHMENTS TO IDENTIFY IF ATTACHED, OR DETACHED.
                jQuery('.attachmentStatus').each(function(index) {
                    
                    tempString = this.value;
                    var subStr = tempString.split('_');
                    
                    if (subStr[0] == 'Detached') {
                        detachedString = detachedString + subStr[1] + ',';
                        detachedCount++;
                    }
                    
                    else if (subStr[0] == 'Attached') {
                        attachedString = attachedString + subStr[1] + ',';
                        attachedCount++;
                    }
                    
                    else if (subStr[0] == 'Merged') {
                        mergedString = mergedString + subStr[1] + ',';
                        mergedCount++;
                    }
                    
                    else if (subStr[0] == 'Added') {
                        addedString = addedString + subStr[1] + ',';
                        addedDocSetupIdString = addedDocSetupIdString + jQuery("#docSetupId_" + subStr[1]).val() + ',';
                        addedCount++;
                    }
                }); // END OF JQUERY EACH (ITERATION OF ALL ATTACHMENTS)
                
                //CONNECT TO AJAX recordViewPageActions.php
                jQuery.ajax({
                    type : 'POST',
                    url : 'ajaxRequests/recordViewPageActions.php',
                    dataType : 'json',
                    data: {
                        action : buttonValue,
                        documentId : "<?php echo $documentId; ?>",
                        selectedSubRouteId : jQuery("#documentRoute").val(),
                        currentSubRouteId : subRouteStringJS,
                        
                        attachedCount : attachedCount,
                        detachedCount : detachedCount,
                        mergedCount : mergedCount,
                        addedCount : addedCount,
                        
                        attachedString : attachedString,
                        detachedString : detachedString,
                        mergedString : mergedString,
                        addedString : addedString,
                        addedDocSetupIdString : addedDocSetupIdString,
                        
                        message : jQuery("#textAreaRemarks").val()
                    },
                    success : function(data){
                        dashboardMessage = "";
                        
                        // SAVES THE DASHBOARD MESSAGES TO VARIABLE dashboardMessage
                        switch(buttonValue) {
                            case "Send" : dashboardMessage = "You have successfully sent main document (<?php echo $documentId; ?>)."; break;
                            case "Approve" : dashboardMessage = "You have successfully approved main document (<?php echo $documentId; ?>)."; break;
                            case "Return For Revisions" : dashboardMessage = "You have successfully returned main document (<?php echo $documentId; ?>) for revisions.";break;
                            case "Disapprove" : dashboardMessage = "You have successfully disapproved main document (<?php echo $documentId; ?>).";break;
                            case "Cancel Transaction" : dashboardMessage = "You have successfully cancelled main document (<?php echo $documentId; ?>).";break;
                            case "Archive" : dashboardMessage = "You have successfully archived main document (<?php echo $documentId; ?>).";break;
                            case "Send " : dashboardMessage = "You have successfully sent main document (<?php echo $documentId; ?>) for archiving.";break;
                            case "Keep" : dashboardMessage = "You put main document (<?php echo $documentId; ?>) and its attachments on hold.";break;
                        }
                        
                        // SAVE DASHBOARD MESSAGE
                        jQuery("#dashboardMessage").val(dashboardMessage);

                        // SUBMIT FORM
                        jQuery("#dashboardMessageForm").submit();
                    },
                    error : function() {
                        alert("fail");
                    }
                });
            } // [END] recordViewPageActions FUNCTION
            
            // [Start] - Function for modifying the attachmentStatus after sent attachment
            function modifyAttchTransacBtn(attchId, action) {
                buttonId = "attchTransacBtn_" + attchId;
                jQuery("#"+buttonId).hide();    // Hide the sent attachment
                jQuery("#attachmentStatus_"+attchId).val(action+"_"+attchId);    // update attachmentStatus of that attachment
            } // [End] - function for modifying the attachmentStatus after sent attachment
            
            // [Start] - GET EXISTING REMARKS
            function getExistingRemarks() {
                // GET EXISTING REMARKS OF THIS DOCUMENT.
                jQuery.ajax({
                    type : 'POST',
                    url : 'ajaxRequests/getRemarks.php',
                    dataType : 'json',
                    async : false,
                    data: {
                        documentId : "<?php echo $documentId; ?>"
                    },
                    success : function(data){
                        if (data) {
                            jQuery.each(data, function(index, data) {
                                jQuery("#lastRemark").before("<tr><td><span style='font-weight:bold;'>"+data.userFullName+" : </span><br><span>"+data.remark+"</span></td><td>"+data.remarkDateTime+"</td></tr>");
                            });

                            jQuery("#noRemarkDefault").hide();
                        }     

                        else {
                            jQuery("#noRemarkDefault").show();
                            jQuery("#remarkHeader").hide();

                        }
                    },
                    error : function() {
                        alert("fail [getRemarks.php AJAX]");
                    }
                });
            }
            
            // JS_DATETIME
            function JS_DateTime()
            {
                var dateT = new Date();
                dateTime = dateT.getFullYear()
                + '-' + (dateT.getMonth()+1)
                + '-' + (dateT.getDate())
                + ' ' + (dateT.getHours())
                + ':' + (dateT.getMinutes())
                + ':' + (dateT.getSeconds());
                return dateTime;
            }    
            
            /*******************************************************************/
            /********************* [END] FUNCTIONS LIST ************************/
            /*******************************************************************/
            
           
           
           
        }); // END - (DOCUMENT READY FUNCTION)
    </script>
    <!-- HEAD END -->


<?php include("siteMiddle.php"); ?>
    
<!-- START OF BODY -->

<div id="content">
    <h1>Document View Page</h1>
    
    <?php
    // Check permission
    $thePermissions = array('VIEWMAIN');
    if ( checkPermission( $thePermissions, $userId ) == true ) {
    ?>
    
    <form>
        <span class="screenlet" >Document Information</span>
        <table>
            <tr></tr>
            <tr><td>Document Type :</td>
                <td>
                    Main Document
                </td>
            </tr>
            
            <tr><td>Document Name :</td>
                <td>
                    <?php echo $documentName; ?>
                </td>
            </tr>

            <tr><td>Document Route :</td>
                <td>
                    <?php echo $routeName; ?>
                </td>
            </tr>
                
            <tr><td>Document ID :</td>
                <td>
                    <?php echo $documentId; ?>
                </td>
            </tr>
            
            <tr>
                <td>Document Labels :</td>
                <td>
                    <?php
                        // Add label of the document. 
                        // Include was done since it is both using by: viewPageSending and viewPageReceiving
                        $mainDocId = $documentId;
                        include('includes/functions/showLabels.php'); 
                    ?>
                </td>
            </tr>
            
            <tr><td>Document Status :</td>
                <td>
                    <span id="docAction" class=""><?php echo $documentAction; ?></span>
                </td>
            </tr>
           
            <?php if ($docStatus == 'Active') { ?>
            <tr><td>User Activity :</td>
                <td>
                    <?php echo $userActivity; ?>
                </td>
            </tr>
            <?php } ?>
        </table>
        
        <!-- START - DISPLAY LOGS OF THE MAIN DOCUMENT ALONG THE TRACK DOCUMENT -->
        <?php include("displayLogs.php");  ?>
        <!-- END - DISPLAY LOGS OF THE MAIN DOCUMENT ALONG THE TRACK DOCUMENT -->
        
        <table class="attachmentRemarkTable" style="border:0;" height="20%" width="100%">
            <tr>
                <td id="attachmentsTD" valign="top" style="padding-left:0; padding-right: 0; padding-top: 0; padding-bottom: 0; width:45%;">
                    <div id="attachmentsScreenlet">
                    <span class="screenlet" >Attachments</span>
                    <table border="1" style="padding-left:0; padding-right: 0; padding-top: 0;">
                        <tr>
                            <tr>
                                <td colspan="3">
                                    <b><u>Required Attachments :</u></b> 
                                    <div id="reqdAttachments"></div>
                                    <br>
                                    <hr style="margin-bottom:2%;">

                                    <div style="margin-bottom:2%;"> Others: <input type="button" style='margin-right:40%;float:right;font-size:10px; padding-right: 1px;padding-left: 1px;padding-top: 1px;padding-bottom: 1px;' class ="siteGreenButton addAttachmentButton" id="addAttachmentButton" value="Add"></div>
                                </td>
                            </tr>
                        </tr>
                        <tr>
                            <th>Document ID</th>
                            <th>Document Name</th>
                            <th>Action</th>
                        </tr>
                        <tr id="lastRowAttachment"></tr>
                    </table>
                    </div>
                </td>
                <td valign="top" style="padding-right: 0; padding-top: 0; padding-bottom: 0; width:55%;">
                    <span class="screenlet">Remarks</span>
                    <div id="remarkScreenlet"  style="width:100%; height:90%; overflow:auto;">
                    <table border="1" style="padding-left:0; padding-right: 0; padding-top: 0; width:100%; ">

                            
                            <tr id="remarkHeader">
                                <th width="80%">Remark</th>
                                <th width="20%">Date Time</th>
                            </tr>
                            <tr id="noRemarkDefault">
                                <td colspan="2">
                                    No remarks for this document.
                                </td>
                            </tr>
                            <tr id="lastRemark"/>
                            
                            <?php if ($docStatus == 'Active') { ?>
                            <tr>
                                <td colspan="2">
                                    <textarea id="remarkInput" style="width:100%; border:none;">Write a remark.</textarea>
                                </td>
                            </tr>
                            <?php  } ?>
                    </table>
                    </div>
                </td>
            </tr>
        </table>
        
        <!-- Choosing a Subroute  -->
        <div id ="subRouteScreenlet">
            <span class="screenlet" >Select Route</span>
            <table border="1">
                <tr>
                    <td> Document Route : 
                        <select name="documentRoute" id="documentRoute" class="documentRouteList">    
                            <option id="defaultSubRoute" value=""></option>
                        </select>
                    </td>
                </tr>
            </table>
        </div>

    <!-- NORMAL SEND BUTTON -->
    <input type="Button" name="sendButton" id="sendButton" class="siteGreenButton viewPageButtons" value="Send" style="display:none;" />
     
    <!-- APPROVE/RETURN FOR REVISIONS/DISAPPROVE BUTTONS -->
    <input type="Button" name="approveButton" id="approveButton" class="siteGreenButton evaluateButtons viewPageButtons" value="Approve" style="display:none;" />
    <input type="Button" name="disapproveButton" id="returnForRevisionsButton" class="siteRedButton evaluateButtons viewPageButtons" value="Return For Revisions" style="display:none;"/>
    <input type="Button" name="disapproveButton" id="disapproveButton" class="siteRedButton evaluateButtons viewPageButtons" value="Disapprove" style="display:none;"/>
    
    <!-- CANCEL BUTTON -->
    <input type="Button" name="cancelButton" id="cancelButton" class="siteRedButton viewPageButtons" value="Cancel Transaction" style="display:none;" />
    
    <!-- ARCHIVE BUTTON -->
    <input type="Button" name="archiveButton" id="archiveButton" class="siteGreenButton viewPageButtons" value="Archive" style="display:none;"/>

    <!-- SEND (CANCELLED) -->
    <input type="Button" name="sendForArchivingButton" id="sendForArchivingButton" class="siteGreenButton viewPageButtons" value="Send " style="display:none;"/>
    
    
    <textarea style="display:none;" rows='4' cols='69' style='background-color: khaki' id='textAreaRemarks'></textarea>
    
    <!-- KEEP BUTTON -->
    <input type="Button" name="keepButton" id="keepButton" class="siteGreenButton viewPageButtons" value="Keep" style="float:right; display:none;"/>
    
    
    <!-- DASHBOARD BUTTON -->
    <input type="Button" name="dashboardButton" id="dashboardButton" class="siteGreenButton" value="Dashboard" style="float:right;"/>
    
    <!-- PLEASE WAIT DIV -->
    <div id="plsWaitDiv" style="display: none;">
        <img src='images/others/loading_1.gif' height='15px' width='15px' /> Please wait
    </div>
    
    <!-- DASHBOARD MESSAGE FORM -->
    </form>
    <form id="dashboardMessageForm" action="dashboard.php" method="POST" target="_self">
        <input type="hidden" name="successMessages" id="dashboardMessage"value=""/>
    </form>
        
    <?php
    }
    else {
        echo "<div class='noPermissionMsgBox noPermissionMsg' style='border: 2px solid red'><div id='noPermissionMsgs'>You have no permission to view this page.</div></div>";
    }
    // End checking permission
    ?>
</div>  

<?php 

    // free result and close database
    mysql_free_result($result);
   
    include ("siteBottom.php");
}   // End - Checker for those users who will just go to the page by typing directly in the url.
else {
 echo "You are not authorized to view this page. This incident will be reported immediately.";
}
?>
